<template>
  <div class="container">
    <div class="topTitle">
      数据列表
    </div>
    <div class="selectOption">
      <div class="elSelect">
        <el-select v-model="checkMonitor" placeholder="Select" size="default" style="width: 240px">
          <el-option v-for="(item, idx) in monitorArr" :key="item" :label="item" :value="item" />
        </el-select>
      </div>
      <div class="elDatePicker">
        <el-date-picker v-model="duringTime" type="daterange" range-separator="To" start-placeholder="Start date"
          end-placeholder="End date" size="default" />
      </div>
      <div class="elBtn">
        <el-button type="primary" @click="searchByTime">搜索</el-button>
      </div>
      <div class="elBtn">
        <el-button type="primary" @click="exportToExcel">导出EXCEL</el-button>
      </div>
    </div>
    <div class="content">
      <div class="tableInner">
        <el-table :data="showDataArr" :header-cell-style="{ textAlign: 'center', fontWeight: 700 }"
          :cell-style="{ textAlign: 'center' }" :max-height="tableHeight" ref="table" style="width: 100%;">
          <el-table-column v-for="column in columnData" :prop="column.prop" :label="column.label" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, inject, nextTick, onMounted, onUnmounted, reactive, ref, toRaw, watch } from 'vue';
import { reqMonitorDuringTimeData } from '@/api/monitor'
import { formatISODateToString } from '@/constant/date'
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
import useOperationStore from '../../../../../store/operation';

// 切换业务的数据对接处理
let operationStore=useOperationStore()
let operationId = ref(operationStore.data.length>0?operationStore.data[operationStore.index].id:'')
operationStore.$subscribe(async(mutation, state)=>{
  operationId.value=operationStore.data[operationStore.index].id
  await initData()
})
// el-table相关
let table = ref()
let tableHeight = computed(() => {
  return screen.height * 0.7
})
const handleResize = function () {
  nextTick(() => {
    table.value.doLayout()
  })
}
const columnData = ref([
  {
    prop: 'soilEcValue',
    label: '土壤EC值(us/cm)'
  },
  {
    prop: 'airTemperature',
    label: '气温(°c)'
  },
  {
    prop: 'airHumidity',
    label: '空气湿度(%)'
  },
  {
    prop: 'lightIntensity',
    label: '光照强度(Lx)'
  },
  {
    prop: 'carbonDioxide',
    label: '二氧化碳(ppm)'
  },
  {
    prop: 'soilTemperature',
    label: '土壤温度(°c)'
  },
  {
    prop: 'soilMoisture',
    label: '土壤水分(%)'
  },
  {
    prop: 'createTime',
    label: '创建时间'
  },
])
// 导出表格
const exportToExcel = () => {
  let newTableData = resetTableData()
  // 假设 this.showDataArr 是你的表格数据，每一项是一个对象，对应表格的一行
  //处理表格数据得到数据
  const worksheet = XLSX.utils.json_to_sheet(newTableData);
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  const excelBuffer = XLSX.write(workbook, {
    bookType: 'xlsx',
    type: 'array'
  });
  // 将缓冲区转换为 Blob 并保存为文件
  const data = new Blob([excelBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  });
  FileSaver.saveAs(data, 'monitorData.xlsx');
}

const resetTableData = () => {
  const propToLabelMap = new Map(columnData.value.map(item => [item.prop, item.label]));
  const restructuredTableData = []
  showDataArr.value.map(row => {
    // 使用映射表创建新对象，其中键为label值，值为原对象的相应prop值
    const newRow = {};
    for (const prop in row) {
      if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
        newRow[propToLabelMap.get(prop)] = row[prop];
      }
    }
    restructuredTableData.push(newRow)
  })
  return restructuredTableData
}
// 获取数据的时间段
let duringTime = ref('')
// 下拉菜单选中值
let checkMonitor = ref('全部')
// 下拉菜单可选值
let monitorArr = computed(() => {
  let arr = ['全部']
  arr.push(...monitorData.map((item) => item.deviceName))
  return arr
})
// 所有请求数据
let monitorData = reactive([])
// 展示的数据
let showDataArr = computed(() => {
  if (checkMonitor.value == '全部') return monitorData.flatMap((item) => item.processedMonitorDataDoList)
  return monitorData.find(item => item.deviceName == checkMonitor.value).processedMonitorDataDoList
})
// 处理后的时间存放处
let startTime = ref('')
let endTime = ref('')
// 请求数据
const initData = async () => {
  if (operationId.value) {
    let res = await reqMonitorDuringTimeData(operationId.value, startTime.value, endTime.value)
    switch (res.code) {
      case 0:
        monitorData.splice(0, monitorData.length)
        monitorData.push(...res.data)
        break;
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break;
    }
  }
}
// 搜索点击监听
const searchByTime = async () => {
  if (duringTime.value) {
    startTime.value = formatISODateToString(duringTime.value[0])
    endTime.value = formatISODateToString(duringTime.value[1])
  }
  await initData()
}
onMounted(async () => {
  window.addEventListener('resize', handleResize)
  await initData()
})
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
@use "@/styles/themes.scss";

.container {
  flex: 1;
  border-radius: 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  flex-direction: column;

  .topTitle {
    height: 4%;
    padding: 0 10px;
    border-left: 3px solid var(--primary-color);
    display: flex;
    align-items: center;
  }

  .selectOption {
    height: 6%;
    display: flex;
    justify-content: right;
    align-items: center;

    .elSelect {
      width: 16%;
      display: flex;
      margin: 0 1%;
    }

    .elDatePicker {
      width: 40%;
      display: flex;
      margin: 0 1%;
    }

    .elBtn {
      display: flex;
      margin: 0 1%;
    }
  }

  .content {
    margin-top: 5px;
    flex: 1;
    display: flex;
    position: relative;

    .tableInner {
      width: 100%;
      position: absolute;
    }
  }
}
</style>